import sys
import configparser
from topicUI import *


class Topic(Ui_Form):
    def __init__(self):
        """
        初始化
        """
        self.ser = ''
        self.log = ''
        self.rstCallback = ''
        self.Form = QtWidgets.QWidget()
        self.setupUi(self.Form)

    def init(self):
        """
        初始化（续）
        :return:
        """
        self.readini()
        self.clearTable()
        self.TopicTable()

    def readini(self):
        """
        读取topic列表
        :return:
        """
        try:
            conf = configparser.ConfigParser()
            conf.read('./TopicParams.ini', encoding="utf-8")
            self.topicDict = {}
            for item in conf.items("TopicParams"):
                self.topicDict[item[0]] = item[1]
            self.log.tempFileLog(f'获取topic列表：{self.topicDict}')
            self.log.runFileLog(f'获取topic列表成功')
        except Exception as e:
            self.log.exceptFileLog(f'获取topic列表出错，错误原因：{e}')

    def TopicTable(self):
        """
        向表格添加数据
        :return:
        """
        self.topic_TW.setColumnCount(3)
        self.topic_TW.setHorizontalHeaderLabels(['变量', '值', '操作'])
        self.topic_TW.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        for key, value in list(self.topicDict.items()):
            self.topic_TW.setRowCount(self.topic_TW.rowCount() + 1)
            keyItem = QtWidgets.QTableWidgetItem(key)
            valueItem = QtWidgets.QTableWidgetItem(value)
            self.topic_TW.setItem(self.topic_TW.rowCount() - 1, 0, keyItem)
            self.topic_TW.setItem(self.topic_TW.rowCount() - 1, 1, valueItem)
            self.topic_TW.setCellWidget(self.topic_TW.rowCount() - 1, 2, self.buttonForRow(self.topic_TW.rowCount()))

    def clearTable(self):
        """
        清空表格数据
        :return:
        """
        row = self.topic_TW.rowCount()
        for r in range(0, row)[::-1]:
            self.topic_TW.removeRow(r)

    def insertTopic(self):
        """
        插入topic
        :return:
        """
        self.topic_TW.setRowCount(self.topic_TW.rowCount() + 1)
        keyItem = QtWidgets.QTableWidgetItem('topicName')
        valueItem = QtWidgets.QTableWidgetItem('topicValue')
        self.topic_TW.setItem(self.topic_TW.rowCount() - 1, 0, keyItem)
        self.topic_TW.setItem(self.topic_TW.rowCount() - 1, 1, valueItem)
        self.topic_TW.setCellWidget(self.topic_TW.rowCount() - 1, 2, self.buttonForRow(self.topic_TW.rowCount()))

    def buttonForRow(self, row):
        """
        自定义行按钮
        :param row: 行号
        :return: 行按钮
        """
        widget = QtWidgets.QWidget()
        # get
        getBtn = QtWidgets.QPushButton('获取')
        getBtn.setStyleSheet("/*按钮普通态*/\n"
                                "QPushButton {\n"
                                "    /*字体为微软雅黑*/\n"
                                "    font-family: Microsoft Yahei;\n"
                                "    /*字体大小为20点*/\n"
                                "    font-size: 11pt;\n"
                                "    /*字体颜色为白色*/\n"
                                "    color: #000000;\n"
                                "    /*背景颜色*/\n"
                                "    background-color: #12A324;\n"
                                "    outline: none;\n"
                                "    border-radius: 5px;\n"
                                "    border: 1px solid #dddddd;\n"
                                "    min-height:1.5em;\n"
                                "    max-width:4em;\n"
                                "    background:#12A324;\n"
                                "    color:#fff;\n"
                                "}\n"
                                "QPushButton:hover {\n"
                                "    border: 1px solid #7084D4;\n"
                                "}\n"
                                "QPushButton:pressed {\n"
                                "    padding-left: 3px;\n"
                                "    padding-top: 3px;\n"
                                "}")

        getBtn.clicked.connect(lambda: self.getTopic(row))

        # set
        setBtn = QtWidgets.QPushButton('设置')
        setBtn.setStyleSheet("/*按钮普通态*/\n"
                             "QPushButton {\n"
                             "    /*字体为微软雅黑*/\n"
                             "    font-family: Microsoft Yahei;\n"
                             "    /*字体大小为20点*/\n"
                             "    font-size: 11pt;\n"
                             "    /*字体颜色为白色*/\n"
                             "    color: #000000;\n"
                             "    /*背景颜色*/\n"
                             "    background-color: #12A324;\n"
                             "    outline: none;\n"
                             "    border-radius: 5px;\n"
                             "    border: 1px solid #dddddd;\n"
                             "    min-height:1.5em;\n"
                             "    max-width:4em;\n"
                             "    background:#12A324;\n"
                             "    color:#fff;\n"
                             "}\n"
                             "QPushButton:hover {\n"
                             "    border: 1px solid #7084D4;\n"
                             "}\n"
                             "QPushButton:pressed {\n"
                             "    padding-left: 3px;\n"
                             "    padding-top: 3px;\n"
                             "}")

        setBtn.clicked.connect(lambda: self.setTopic(row))

        # read
        readBtn = QtWidgets.QPushButton('读取')
        readBtn.setStyleSheet("/*按钮普通态*/\n"
                             "QPushButton {\n"
                             "    /*字体为微软雅黑*/\n"
                             "    font-family: Microsoft Yahei;\n"
                             "    /*字体大小为20点*/\n"
                             "    font-size: 11pt;\n"
                             "    /*字体颜色为白色*/\n"
                             "    color: #000000;\n"
                             "    /*背景颜色*/\n"
                             "    background-color: #12A324;\n"
                             "    outline: none;\n"
                             "    border-radius: 5px;\n"
                             "    border: 1px solid #dddddd;\n"
                             "    min-height:1.5em;\n"
                             "    max-width:4em;\n"
                             "    background:#12A324;\n"
                             "    color:#fff;\n"
                             "}\n"
                             "QPushButton:hover {\n"
                             "    border: 1px solid #7084D4;\n"
                             "}\n"
                             "QPushButton:pressed {\n"
                             "    padding-left: 3px;\n"
                             "    padding-top: 3px;\n"
                             "}")

        readBtn.clicked.connect(lambda: self.readTopic(row))

        # write
        writeBtn = QtWidgets.QPushButton('写入')
        writeBtn.setStyleSheet("/*按钮普通态*/\n"
                             "QPushButton {\n"
                             "    /*字体为微软雅黑*/\n"
                             "    font-family: Microsoft Yahei;\n"
                             "    /*字体大小为20点*/\n"
                             "    font-size: 11pt;\n"
                             "    /*字体颜色为白色*/\n"
                             "    color: #000000;\n"
                             "    /*背景颜色*/\n"
                             "    background-color: #12A324;\n"
                             "    outline: none;\n"
                             "    border-radius: 5px;\n"
                             "    border: 1px solid #dddddd;\n"
                             "    min-height:1.5em;\n"
                             "    max-width:4em;\n"
                             "    background:#12A324;\n"
                             "    color:#fff;\n"
                             "}\n"
                             "QPushButton:hover {\n"
                             "    border: 1px solid #7084D4;\n"
                             "}\n"
                             "QPushButton:pressed {\n"
                             "    padding-left: 3px;\n"
                             "    padding-top: 3px;\n"
                             "}")

        writeBtn.clicked.connect(lambda: self.writeTopic(row))

        # delete
        deleteBtn = QtWidgets.QPushButton('删除')
        deleteBtn.setStyleSheet("/*按钮普通态*/\n"
                               "QPushButton {\n"
                               "    /*字体为微软雅黑*/\n"
                               "    font-family: Microsoft Yahei;\n"
                               "    /*字体大小为20点*/\n"
                               "    font-size: 11pt;\n"
                               "    /*字体颜色为白色*/\n"
                               "    color: #000000;\n"
                               "    /*背景颜色*/\n"
                               "    background-color: #12A324;\n"
                               "    outline: none;\n"
                               "    border-radius: 5px;\n"
                               "    border: 1px solid #dddddd;\n"
                               "    min-height:1.5em;\n"
                               "    max-width:4em;\n"
                               "    background:#12A324;\n"
                               "    color:#fff;\n"
                               "}\n"
                               "QPushButton:hover {\n"
                               "    border: 1px solid #7084D4;\n"
                               "}\n"
                               "QPushButton:pressed {\n"
                               "    padding-left: 3px;\n"
                               "    padding-top: 3px;\n"
                               "}")

        deleteBtn.clicked.connect(lambda: self.deleteTopic(row))

        hLayout = QtWidgets.QHBoxLayout()
        # hLayout.addWidget(getBtn)
        # hLayout.addWidget(setBtn)
        hLayout.addWidget(readBtn)
        hLayout.addWidget(writeBtn)
        hLayout.addWidget(deleteBtn)
        hLayout.setContentsMargins(5, 2, 5, 2)
        widget.setLayout(hLayout)
        return widget

    def readTopic(self, row):
        """
        读取topic
        :param row:
        :return:
        """
        try:
            key = self.topic_TW.item(row-1, 0).text()
            conf = configparser.ConfigParser()
            conf.read('./TopicParams.ini', encoding="utf-8")
            newValue = conf.get('TopicParams', key)
            newValueItem = QtWidgets.QTableWidgetItem(newValue)
            self.topic_TW.setItem(row - 1, 1, newValueItem)
            self.log.tempFileLog(f'从文件./TopicParams.ini读取信息：{key}={newValue}')
            self.log.runFileLog('读取成功')
        except Exception as e:
            self.log.exceptFileLog(f'读取出错，错误原因：{e}')

    def writeTopic(self, row):
        """
        写入topic
        :param row:
        :return:
        """
        try:
            key = self.topic_TW.item(row - 1, 0).text()
            value = self.topic_TW.item(row - 1, 1).text()
            conf = configparser.ConfigParser()
            conf.read('./TopicParams.ini', encoding="utf-8")
            conf.set('TopicParams', key, value)
            conf.write(open('./TopicParams.ini', "w+", encoding="utf-8"))
            self.log.tempFileLog(f'向文件./TopicParams.ini写入信息：{key}={value}')
            self.log.runFileLog('写入成功')
        except Exception as e:
            self.log.exceptFileLog(f'写入出错，错误原因：{e}')

    def getTopic(self, row):
        """
        获取topic
        :param row:
        :return:
        """
        try:
            key = self.topic_TW.item(row-1, 0).text()
            newValue = self.ser.PubSub(data=f'AT+GET{key.upper()}')
            newValueItem = QtWidgets.QTableWidgetItem(newValue)
            self.topic_TW.setItem(row-1, 1, newValueItem)
            self.log.tempFileLog(f'获取信息：{key}={newValue}')
            self.log.runFileLog('获取成功')
        except Exception as e:
            self.log.exceptFileLog(f'获取出错，错误原因：{e}')

    def setTopic(self, row):
        """
        提交topic
        :param row:
        :return:
        """
        key = self.topic_TW.item(row - 1, 0).text()
        value = self.topic_TW.item(row - 1, 1).text()
        result = self.ser.PubSub(data=f'AT+{key.upper()}={value}')
        print(result)

    def deleteTopic(self, row):
        try:
            key = self.topic_TW.item(row - 1, 0).text()
            conf = configparser.ConfigParser()
            conf.read('./TopicParams.ini', encoding="utf-8")
            conf.remove_option('TopicParams', key)
            conf.write(open('./TopicParams.ini', "w+", encoding="utf-8"))
            self.init()
            self.log.tempFileLog(f'删除topic：{key}')
            self.log.runFileLog(f'删除成功')
        except Exception as e:
            self.exceptFileLog(f'删除出错，错误原因：{e}')


    def rst(self):
        self.rstCallback()


if __name__ == '__main__':
    def rst():
        print('复位')
    from serialUtil import *
    ser = SerialUtil(port='COM6', bps=115200, timeout=0.5)
    from runTimeLogUiUtil import RunTimeLogUiUtil
    app = QtWidgets.QApplication(sys.argv)
    log = RunTimeLogUiUtil()
    tc = Topic()
    tc.rstCallback = rst
    tc.ser = ser
    tc.log = log
    tc.init()
    tc.Form.show()
    sys.exit(app.exec_())